<script setup>
import { ref, onMounted, computed } from 'vue'
import * as funCommon from "@/apis/common"

const emits = defineEmits(["emitImageUrls", "emitImageUrls"])

const props = defineProps({
    folder: String,
    fileName: String,
    imageUrls: Array,
    justQuery: Boolean,
    multiple: Boolean
})

const uploadHeaders = $Common.uploadHeaders()
const uploadUrl = ref("")
const uploadData = ref({
    ContainerName: props.folder || "",
    Name: props.fileName || ""
})
const previewUrls = ref([])
const uploadMultiple = props.multiple || false

onMounted(() => {
    // 数据初始化
    uploadUrl.value = $Common.uploadBaseUrl + "/files"
})

const imgUrls = computed(() => {
    let imgs = []
    imgs = props && props.imageUrls.map(x => {
        let url = $Tools.isUrl(x) ? x : ($Common.uploadBaseUrl + x)
        return url
    })
    return imgs
})

const beforeAvatarUpload = (file) => {
    const isLt2M = file.size / 1024 / 1024 < 10
    if (!isLt2M) {
        $Common.errorMsg('上传图片大小不能超过 10MB!')
        return false
    }
    $Common.fullLoading()
    return true
}

const handleAvatarSuccess = (res, file, fileList, index) => {
    console.log(res, file, fileList, index)
    $Common.closeFullLoading()
    emitImageUrls(index, res.url)
}

const handleAvatarError = () => {
    $Common.closeFullLoading()
}

const setPreviewUrls = () => {
    previewUrls.value = []
    setTimeout(() => {
        previewUrls.value = imgUrls.value || []
    }, 100)
}

const movePrev = (index) => {
    if (index < 1) {
        $Common.warningMsg("已是第一个!")
        return false
    }
    $Common.swiperSort(imgUrls.value, index, index - 1)
    emitAllImages()
}

const moveNext = (index) => {
    if (index >= imgUrls.value.length - 1) {
        $Common.warningMsg("已是最后一个!")
        return false
    }
    $Common.swiperSort(imgUrls.value, index, index + 1)
    emitAllImages()
}

const deleteUrl = (index) => {
    // 删除服务器的图片
    funCommon.delBlob(imgUrls.value[index].replace($Common.uploadBaseUrl, "")).then(res => {
        // 删除
        emitImageUrls(index, null)
    }).catch(ex => {
        // 删除
        emitImageUrls(index, null)
    })
}

const emitAllImages = () => {
    emits("emitImageUrls", -1, "", imgUrls.value)
}

const emitImageUrls = (index, url) => {
    emits("emitImageUrls", index !== undefined ? index : -1, url)
}
</script>

<template>
    <div class="comp-drag-multiple-imageupload">
        <div class="images" v-for="(img, index) in imgUrls" :key="img">
            <el-image class="image" :src="img" :preview-src-list="previewUrls" @click="setPreviewUrls" :z-index="9999999990"></el-image>
            <div class="btns" v-if="!justQuery">
                <el-upload class="btn edit" :show-file-list="false" title="修改"
                    accept="image/jpeg,image/gif,image/png"
                    :headers="uploadHeaders"
                    :action="uploadUrl" 
                    :data="uploadData"
                    :on-success="(res, file, fileList) => { handleAvatarSuccess(res, file, fileList, index) }"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload">
                    <template>
                        <el-icon><EditPen /></el-icon>
                    </template>
                </el-upload>
                <a class="btn prev" @click="movePrev(index)" title="左移" v-if="index > 0"><el-icon><Back /></el-icon></a>
                <a class="btn next" @click="moveNext(index)" title="右移" v-if="index < imgUrls.length - 1"><el-icon><Right /></el-icon></a>
                <a class="btn del" @click="deleteUrl(index)" title="删除"><el-icon><DeleteFilled /></el-icon></a>
            </div>
        </div>
        <template v-if="!justQuery">
            <el-upload class="upload-btn" :show-file-list="false" :multiple="uploadMultiple"
                accept="image/jpeg,image/gif,image/png"
                :headers="uploadHeaders"
                :action="uploadUrl" 
                :data="uploadData"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload">
                <el-icon><Plus /></el-icon>
            </el-upload>
        </template>
        <div class="clearb"></div>
    </div>
</template>

<style lang="scss">
.comp-drag-multiple-imageupload {
    .upload-btn {
      float: left;
    }
    .upload-btn .el-upload {
      width: 100px;
      height: 100px;
      line-height: 100px;
      border: 1px dotted #999;
      color: #999;
      font-size: 32px;
      font-weight: normal;
      border-radius: 4px;
    }
    .images {
      margin: 0 10px 10px 0;
      float: left;
      width: 100px;
      height: auto;
      border-radius: 4px;
      position: relative;
      background-color: #f4f4f4;
      .image {
        display: block;
        width: 100px;
        height: 100px;
        background-color: #ffffff;
        border: 1px dotted #f0f9ff;
      }
      .btns {
        display: flex;
        justify-content: space-evenly;
        width: 96px;
        height: 22px;
        padding: 0 2px;
        border: 1px dotted #999;
        border-top: 0;
        align-items: center;
      }
      .btn {
        display: inline-block;
        width: 16px;
        height: 16px;
        line-height: 16px;
        text-align: center;
        background: #fefefe;
        border: 1px solid #ddd;
        cursor: pointer;
      }
      .btn.edit {
        left: 2px;
        color: #1f7dff;
      }
      .btn.prev {
        left: 28px;
      }
      .btn.next {
        right: 28px;
      }
      .btn.del {
        right: 2px;
        color: #ff0000;
      }
    }
}
</style>